package com.snut.tomorrowNews.service.user;

import com.snut.tomorrowNews.dao.front.CommentDao;
import com.snut.tomorrowNews.dao.user.UserDao;
import com.snut.tomorrowNews.model.Collect;
import com.snut.tomorrowNews.model.Comment;
import com.snut.tomorrowNews.model.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户服务层
 *
 * @author Deevan
 */
@Service
@Transactional
public class UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    CommentDao commentDao;

    public void userReg(User user) {
        //加密
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        userDao.insertUser(user);
    }

    /**
     * 用户登录验证
     */
    public User loginUser(User user) {
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        return userDao.checkUserLogin(user);
    }

    /**
     * 查询用户信息
     */
    public User getUserMsg(Integer id) {
        return userDao.getUserById(id);
    }

    /**
     * 修改用户信息
     */
    public void setUserMsg(User user) {
        userDao.setUser(user);
    }

    /**
     * 用户修改密码
     */
    public Integer setPassword(String oldPwd, String newPwd, Integer userId) {
        //查询老密码
        User user = userDao.getUserById(userId);
        String password = user.getPassword();
        //输入的老密码与已存密码是否一致
        if (DigestUtils.md5Hex(oldPwd).equals(password)) {
            user.setId(userId);
            user.setPassword(DigestUtils.md5Hex(newPwd));
            userDao.setUser(user);
            return 1;
        } else {
            return 2;
        }
    }

    /**
     * 获取用户收藏列表
     */
    public List<Collect> getUserCollect(Integer userId) {
        return userDao.getUserCollect(userId);
    }

    /**
     * 获取用户评论列表
     */
    public List<Comment> getUserComment(Integer userId) {
        return commentDao.getUserComment(userId);
    }

    public void deleteCollect(Integer userId, Integer newsId) {
        userDao.deleteCollect(userId, newsId);
    }

    public void deleteComment(Integer commentId) {
        userDao.deleteComment(commentId);
    }

    public void addCollect(Integer userId, Integer collectNewsId) {
        userDao.insertCollect(userId, collectNewsId);
    }

    /**
     * 查询用户列表
     */
    public List<User> filterUserList(Integer userType) {
        return userDao.userList(userType);
    }

    public void updateUserState(Integer userId, Integer state) {
        userDao.updateUserState(userId,state);
    }
}
